package com.zrar.ak.gkpt.controller.common;

import com.zrar.ak.gkpt.model.bo.CommonAnnexInfoBO;
import com.zrar.ak.gkpt.model.vo.UserVO;
import com.zrar.ak.gkpt.service.common.ICommonAnnexInfoService;
import com.zrar.ak.gkpt.service.user.IUserService;
import com.zrar.ak.gkpt.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @ClassName: CommonAnnexInfoController
 * @Description 附件上传和下载操作Controller层
 * @Author liyang
 * @Time 2020/02/25
 */
@RestController
@RequestMapping("/annex")
@Api(tags = "附件上传和下载相关接口")
@Slf4j   //该注解可以进行日志输出  log
public class CommonAnnexInfoController {

    @Autowired
    private ICommonAnnexInfoService annexService;
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "annexUpload", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "附件上传", httpMethod = "POST", notes = "附件上传")
    public JsonResult annexUpload(HttpServletRequest request,
                                            @ApiParam(name = "file", value = "上传的附件") @RequestParam MultipartFile file,
                                            @ApiParam(name = "annexStatus", value = "附件上传状态(1.相关数据待提交 2.相关数据已提交成功 3.无相关数据的附件)") @RequestParam(value = "annexStatus", required = false, defaultValue = "3") String annexStatus){
        JsonResult jsonResult = new JsonResult();
        UserVO userVO = userService.getUserInformation(request);
        jsonResult = annexService.annexUpload(jsonResult, file, annexStatus, userVO);
        return jsonResult;
    }

    @RequestMapping(value = "annexDelete", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "附件删除", httpMethod = "GET", notes = "附件删除")
    public JsonResult annexDelete(HttpServletRequest request,
                                  @ApiParam(name = "id", value = "附件id") @RequestParam String id){
        JsonResult jsonResult = new JsonResult();
        UserVO userVO = userService.getUserInformation(request);
        jsonResult = annexService.annexDelete(jsonResult, id, userVO);
        return jsonResult;

    }



    //注意此处若是通过swagger访问下载文件，汉字文件名会出现乱码，若浏览器直接访问对应的地址，则不会出现乱码
    @RequestMapping(value = "annexDownload", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "附件下载", httpMethod = "GET", notes = "附件下载")
    public void annexDownload(HttpServletRequest request, HttpServletResponse response,
                                        @ApiParam(name = "id", value = "附件id") @RequestParam String id){
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            CommonAnnexInfoBO commonAnnexInfoBO = annexService.getAnnexInfoById(id);
            //读取本地的文件
            File file = new File(commonAnnexInfoBO.getSavePath());
            String annexFullName = commonAnnexInfoBO.getAnnexFullName();
            in = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(response.getOutputStream());
            //设置返回值
            //设置response内容的类型
            response.setContentType(new MimetypesFileTypeMap().getContentType(file));
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(annexFullName, "UTF-8"));
//            res.setHeader("Content-disposition", "attachment;filename="+ fileName);// 设置头部信息
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len=in.read(arr))>0){
                out.write(arr,0,len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("附件下载的接口处理异常",e.getMessage());
        } finally {
            try {
                if (in!=null){
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("附件下载的接口关闭流处理异常",e.getMessage());
            }
        }
    }


    @RequestMapping(value = "annexPreview", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "附件预览", httpMethod = "GET", notes = "附件预览")
    public void annexPreview(HttpServletRequest request, HttpServletResponse response,
                             @ApiParam(name = "id", value = "附件id") @RequestParam String id) {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            CommonAnnexInfoBO commonAnnexInfoBO = annexService.getAnnexInfoById(id);
            //读取本地的文件
            File file = new File(commonAnnexInfoBO.getSavePath());
            String annexFullName = commonAnnexInfoBO.getAnnexFullName();
            in = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(response.getOutputStream());

            //设置响应头，告诉浏览器以下载的方式打来文件，设置中文编码，如果不设置会出现乱码
            response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode(annexFullName, "UTF-8"));
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len = in.read(arr)) != -1) {
                //将缓冲区数据输出到浏览器
                out.write(arr, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("附件预览的接口处理异常",e.getMessage());
        } finally {
            try {
                if (in!=null){
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("附件预览的接口关闭流处理异常",e.getMessage());
            }
        }
    }






}
